import React, { useState, useEffect } from 'react'
import { Table, Switch, Button, message, Drawer, Modal, Tooltip, Tag, Upload } from 'antd';
import { fetchItems, deleteIItem, changeItemDetail, getItemDetail } from '@/api/item'
import SearchBar from '@/components/SearchBar';
import { useNavigate } from 'react-router-dom';
import './itemLists.scss'
import { utils, writeFileXLSX, read } from 'xlsx';

export default function ItemLists() {
    const navigate = useNavigate()
    // 搜索字段
    let serarchParams = {
        key: '',
        start: '',
        end: ''
    }


    // 定义方法获取 商品列表数据, 修改数据
    let page = 1
    let pageSize = 10
    let [total, setTotal] = useState(0)

    // 商品列表数据
    let [items, setItems] = useState([])
    const fetchItemLists = () => {
        fetchItems({
            page,
            pageSize,
            ...serarchParams
        }).then(res => {
            if (res.data.code === 200) {

                setTotal(total = res.data.data.total)
                setItems(items = res.data.data.lists)
                // console.log(cates);
            }
        })
    }

    // table组件, 定义表头和渲染内容
    const columns = [
        {
            title: '商品名',
            dataIndex: 'itemName',
            key: 'itemName',
        },
        {
            title: '价格',
            dataIndex: 'price',
            key: 'price',
            render(price: number) {
                return (
                    <Tag color={price > 1000 ? "green" : "red"}>
                        {price}
                    </Tag>
                )

            }
        },
        {
            title: '销量',
            dataIndex: 'sale',
            key: 'sale',
            render(sale: number) {
                return (
                    <Tag color={sale > 30000 ? "yellow" : "orange"}>
                        {sale}
                    </Tag>
                )

            }
        },
        {
            title: '商品图片',
            dataIndex: 'thumb',
            key: 'thumb',
            render: (thumb: string) => {
                return <img src={thumb} width={50} alt="" />
            }
        },
        {
            title: '上下架',
            dataIndex: 'onsale',
            key: 'onsale',
            render: (onsale: boolean, row: any) => {
                return (
                    <Switch
                        // 下列代码、按钮开关不能点击切换
                        // checked={onsale}
                        checkedChildren="上架"
                        unCheckedChildren="下架"
                        onChange={
                            (checked) => {
                                switchCateonsale(row.id, checked)
                            }
                        } />
                )
            }
        },
        {
            title: '商品描述',
            dataIndex: 'desc',
            key: 'desc',
            render(desc: string) {
                return (
                    <Tooltip title={desc}>
                        {desc.substring(0, 12) + '...'}
                    </Tooltip>
                )
            }
        },
        {
            title: '操作',
            key: 'actions',
            render: (row: any) => {
                return (
                    <>
                        <Button type='primary' onClick={
                            () => {
                                // 编辑修改 携带参数 跳转路由
                                updateItem(row.id)
                            }
                        }>编辑</Button>
                        <Button
                            danger
                            type='primary'
                            onClick={
                                () => {
                                    delItemOne(row.id)
                                }
                            }
                        >
                            删除
                        </Button>
                    </>
                )
            }
        }
    ];

    // 编辑修改商品 跳转传参
    const updateItem = (id: number) => {
        navigate(`/itemUpdate?id=${id}`)
    }

    // 删除商品
    const delItemOne = (id: number) => {
        // setId(id);
        console.log(id);

        Modal.confirm({
            title: '删除',
            content: '确定要删除吗？',
            onOk: () => {
                deleteIItem().then(res => {
                    if (res.data.code === 200) {
                        message.success(res.data.msg, 1.6, () => {
                            navigate(0)
                        })
                    }
                })
            }
        })
    }

    // 修改 是否启用 onsale状态
    const switchCateonsale = (id: number, onsale: boolean) => {
        // console.log(id, onsale);
        changeItemDetail({
            id: id,
            onsale: onsale
        }).then(res => {
            if (res.data.code === 200) {
                message.success(res.data.msg, 1, () => {
                    navigate(0)
                })
            }
        })
    }

    // 点击搜索
    const onSearch = (params: { key: string, start: string, end: string }) => {
        serarchParams = params
        // fetchCates()
        // 搜索成功 全局消息提示
        message.success("搜索成功", 2, () => {
            navigate(0)
        })
    }

    // 定义方法获取 商品列表数据 后, 渲染数据到table
    useEffect(() => {
        fetchItemLists()
    }, [])

    // 列表分页
    const pagination = {
        defaultCurrent: page,
        defaultPageSize: pageSize,
        total,
        onChange: (subPage: number, subPageSize: number) => {
            // 修改page和pageSize
            page = subPage;
            pageSize = subPageSize;
            fetchItemLists()
        }
    }

    // 下载模板 xlsx
    const exportFileXslx = () => {
        const data = [
            {
                商品名: 'Mi 12',
                商品价格: '3999',
                商品描述: '骁龙8 Gen 1'
            }
        ]

        const ws = utils.json_to_sheet(data)
        const wb = utils.book_new()
        utils.book_append_sheet(wb, ws, 'Data')
        writeFileXLSX(wb, '批量新增商品模板.xlsx')
    }

    // 批量新增
    const uploadFileXlsx = (xlsxs: any) => {
        const fd = new FileReader()
        fd.readAsArrayBuffer(xlsxs)
        fd.onload = () => {
            const wb = read(fd.result)
            const data = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
            const subData = data.map(itemEl => {
                return {
                    itemName: itemEl.商品名,
                    price: itemEl.商品价格,
                    desc: itemEl.商品描述
                }
            })
            console.log(subData);
            message.success('批量上传成功', 1, () => {
                navigate(0)
            })

        }
        return false
    }


    return (
        <div>
            <>
                {/* SearchBar搜索组件 */}
                <SearchBar onSearch={onSearch} />
            </>

            <div className='newItem'>
                <>
                    {/* 增加商品的路由按钮 */}
                    <Button type='primary' id='antBtnAddCate' onClick={
                        () => {
                            navigate('/itemAdd')
                        }
                    } >
                        单个新增商品
                    </Button>
                </>
                <div className='excelXlsx'>
                    <Upload
                        showUploadList={false}
                        action="#"
                        accept='.xlsx, .lsx'
                        beforeUpload={uploadFileXlsx}
                    >
                        <Button type='primary'>点击上传批量新增商品模板</Button>
                    </Upload>
                    <a href="#" onClick={exportFileXslx} >下载模板</a>
                </div>
            </div>

            {/* 商品列表渲染 */}
            <Table
                columns={columns}
                dataSource={items}
                pagination={pagination}
                rowKey='id'
            // 分页
            // pagination={false}
            />

        </div >
    )
}
